import resources.RegistNetPropertyBundle;
import resources.Constants;

import registnet.dao.GradePeer;
import registnet.dao.Grade;
import registnet.dao.StudentPeer;
import registnet.dao.Student;
import registnet.dao.CoursePeer;

/* [start] 	initializes gui variables */
RegistNetPropertyBundle bundle = RegistNetPropertyBundle.getInstance("/resources/registnet");

String _add = bundle.getProperty("registnet.module.data_management.actions.menu.add");
String _edit = bundle.getProperty("registnet.module.data_management.actions.menu.edit");
String _delete = bundle.getProperty("registnet.module.data_management.actions.menu.delete");
String _import = bundle.getProperty("registnet.module.data_management.actions.menu.import");
String _search = bundle.getProperty("registnet.module.data_management.actions.menu.search");
String _show_all = bundle.getProperty("registnet.module.data_management.actions.menu.show_all");

String _students = bundle.getProperty("registnet.module.data_management.macro.grades.form.students");
String _academic_year = bundle.getProperty("registnet.module.data_management.macro.grades.form.academic_year");
String _semester = bundle.getProperty("registnet.module.data_management.macro.grades.form.semester");
String _course = bundle.getProperty("registnet.module.data_management.macro.grades.form.course");
String _section = bundle.getProperty("registnet.module.data_management.macro.grades.form.section");
String _credit = bundle.getProperty("registnet.module.data_management.macro.grades.form.credit");
String _grade = bundle.getProperty("registnet.module.data_management.macro.grades.form.grade");
String _remarks = bundle.getProperty("registnet.module.data_management.macro.grades.form.remarks");
String _submit = bundle.getProperty("registnet.module.data_management.macro.grades.form.submit");
String _cancel = bundle.getProperty("registnet.module.data_management.macro.grades.form.cancel");

String _registrar = Constants.REGISTRAR;
String _college = Constants.COLLEGE;
String _unit = Constants.UNIT;

String _proceed = bundle.getProperty("registnet.messages.proceed");
String _check = bundle.getProperty("registnet.messages.check");
String _successful = bundle.getProperty("registnet.messages.successful");
String _failed = bundle.getProperty("registnet.messages.failed");
String _select_one = bundle.getProperty("registnet.messages.select_one");
String _selected = bundle.getProperty("registnet.messages.selected");
String _use_search_result_viewer = bundle.getProperty("registnet.messages.use_search_result_viewer");

String _icon_add = bundle.getProperty("registnet.icons.add");
String _icon_edit = bundle.getProperty("registnet.icons.edit");
String _icon_delete = bundle.getProperty("registnet.icons.delete");
String _icon_import = bundle.getProperty("registnet.icons.import");
/* [end] */


List grades = new Vector();


/* [start]	*/
ArrayList parentList = new ArrayList();
Map mapSTN_parent = new HashMap();
Map mapAL_parent = new HashMap();
Map mapAL_child = new HashMap();
Map map_treeitem = new HashMap();
SimpleTreeNode root = new SimpleTreeNode("ROOT", parentList);

public class SelectEventListener implements EventListener {
	
	public SelectEventListener (){
	}
			
	public void onEvent(Event event) throws UiException {
		
		if (instance_tree.getSelectedCount() == 1){
			if (instance_tree.getSelectedItem().getParentItem() != null){
				grades = new Vector();
				showInfo();
			}
		}
		else if (instance_tree.getSelectedCount() > 1)
			title.setValue("" + instance_tree.getSelectedCount() + " " + _instance + " selected");
		else
			title.setValue("");
	}
}

public class MyTreeitemRenderer implements TreeitemRenderer {

	public void render(Treeitem item, Object data) throws Exception {
		
		String str = data.toString();
		
		Treerow tr = null;
		
		Treecell tc = new Treecell(str);
		if(item.getTreerow()==null){
			tr = new Treerow();
			tr.setParent(item);
			map_treeitem.put(str, item);
		}else{
			tr = item.getTreerow(); 
			tr.getChildren().clear();
		}
		tc.setParent(tr);
	}
}

public void retrieveObjects(){
	try{
	map_treeitem.clear();
	mapSTN_parent.clear();
	mapAL_parent.clear();
	mapAL_child.clear();
	parentList.clear();
	
	HashMap batch_leaf = new HashMap();
	HashMap batch_child = new HashMap();
	List students;
	
	students = new StudentPeer().getAllStudents();
	/*
	if (_user_type.equals("Registrar"))
		students = studentPeer.getAllStudents();
	else if (_user_type.equals("College"))
		students = studentPeer.getStudentByCollege(new CollegePeer().getCollegeId(_office));
	*/
	for(int i=0; i<students.size(); i++){
		registnet.dao.Student student = students.get(i);
		String batch = student.getStudentNumber().substring(0, 4);
		if (!batch_leaf.containsKey(batch)){
			batch_leaf.put(batch, new ArrayList());
			batch_child.put(batch, new ArrayList());
		}
		SimpleTreeNode stnChild = new SimpleTreeNode(student.getStudentNumber(), new ArrayList());
		batch_leaf.get(batch).add(student.getStudentNumber());
		batch_child.get(batch).add(stnChild);
	}
	
	Set batch_key = batch_leaf.keySet();
	Iterator iter = batch_key.iterator();
	
	while(iter.hasNext()){
		String batch = iter.next();
		SimpleTreeNode stnParent = new SimpleTreeNode(batch, batch_child.get(batch));
		mapSTN_parent.put(batch, stnParent);
		mapAL_parent.put(batch, batch_child.get(batch));
		mapAL_child.put(batch, batch_leaf.get(batch));
		parentList.add(stnParent);
	}

	SimpleTreeNode root = new SimpleTreeNode("ROOT", parentList);
	SimpleTreeModel stm = new SimpleTreeModel(root);
	instance_tree.setModel(stm);
	instance_tree.setTreeitemRenderer(new MyTreeitemRenderer());
	}catch(Exception e){e.printStackTrace();}
}



void showInfo(){
	grades = new GradePeer().getGradeByStudent(new StudentPeer().getStudent(instance_tree.getSelectedItem().getLabel()).getStudentId());
	String[][] listModel = new String[grades.size()][6];
	for(int i=0; i<grades.size(); i++){
		Grade grade = grades.get(i);
		
		String semesterValue;
		String yearValue;
	
		if (grade.getSemester() == Constants.MAP_SEMESTER_KEY.get("SUMMER"))
			yearValue = (grade.getAcademicYear() - 1) + "-" + grade.getAcademicYear();
		else
			yearValue = grade.getAcademicYear() + "-" + (grade.getAcademicYear() + 1);
		
		semesterValue = Constants.MAP_SEMESTER_VALUE.get(grade.getSemester());
			
		listModel[i][0] = yearValue;
		listModel[i][1] = semesterValue;
		listModel[i][2] = grade.getCourse().getCourseCode();
		listModel[i][3] = grade.getSectionName();
		listModel[i][4] = Constants.MAP_GRADE_VALUE.get(grade.getGrade());
		listModel[i][5] = grade.getRemarks();
	}
	ListModel strset = new SimpleListModel(listModel);
	contents_win.getFellow("grades_l").setModel(strset);
	contents_win.getFellow("grades_l").setItemRenderer(new GradesRenderer());
}



/* [start]	defines a renderer for the grades */
private class GradesRenderer implements ListitemRenderer  {
	public void render(Listitem item, java.lang.Object data) {
		new Listcell(data[0]).setParent(item);
		new Listcell(data[1]).setParent(item);
		new Listcell(data[2]).setParent(item);
		new Listcell(data[3]).setParent(item);
		new Listcell(data[4]).setParent(item);
		new Listcell(data[5]).setParent(item);
	}
}
/* [end] */



/* [start]	automatically updates the 'to' value of academic year based on the
			current 'from' value of the academic year */
private void updateAY(){
	try{
		year2.value = (Integer.parseInt(event.value) + 1).toString();
	}catch(Exception e) {year1.value = null; year2.value = null;}
}
/* [end] */



/* [start]	creates a new grades entry in the database;
			removes the selected item from the listbox
			notifies the user if no grade is selected */
void submit(){
	if (isValid()){
		try{
			Integer semesterValue = Constants.MAP_SEMESTER_KEY.get(semester.getSelectedItem().getLabel());
			String remarksValue = remarks.value;
			Double gradeValue = Constants.MAP_GRADE_KEY.get(grade.getSelectedItem().getLabel());
			Integer academicYearValue;
			if (semesterValue == Constants.MAP_SEMESTER_KEY.get(Constants.SUMMER))
				academicYearValue = Integer.parseInt(year2.value);
			else
				academicYearValue = Integer.parseInt(year1.value);
				
			if(grade_id.value != null){
				new GradePeer().updateGrade(grade_id.value, new CoursePeer().getCourseId(course.value), section.value, gradeValue, new StudentPeer().getStudentId(instance_tree.getSelectedItem().getLabel()), semesterValue, academicYearValue, remarks.value, credit.value);
				alert("Edit Grade Successful");
			}
			else{
				new GradePeer().createNewGrade(new CoursePeer().getCourseId(course.value), section.value, gradeValue, new StudentPeer().getStudentId(instance_tree.getSelectedItem().getLabel()), semesterValue, academicYearValue, remarks.value, credit.value);
				alert("Add Grade Successful");
			}

			showInfo();
			cancel();
		}catch(Exception e) { alert("Check information supplied"); }
	}
	else
		alert("Check information supplied");
}
/* [end] */



/* [start]	clears the form;
			closes the form */
void cancel(){
	year1.value = null;
	year2.value = null;
	semester.value = null;
	grade.value = null;
	course.value = null;
	section.value = null;
	credit.value = null;
	remarks.value = null;
	grade_form_popup.close();
}
/* [end] */



boolean isValid(){
	if (year1.value == null)
		return false;
	if (year2.value == null)
		return false;
	if (semester.value == null)
		return false;
	if (grade.value == null)
		return false;
	if (course.value.trim().length() == 0)
		return false;
	if (section.value.trim().length() == 0)
		return false;
	if (credit.value == null || credit.value < 0 || credit.value > 10)
		return false;
	return true;
}


void showForm(String object){
	if (object.equals(_add)){
		if (new StudentPeer().getStudent(instance_tree.getSelectedItem().getLabel()) != null){
			year1.value = null;
			year2.value = null;
			semester.value = null;
			grade.value = null;
			course.value = null;
			section.value = null;
			credit.value = null;
			remarks.value = null;
			grade_id.value = null;
			grade_form_popup.open(self);
		}
		else
			alert("Select a student");
	}
	else if (object.equals(_edit)){
		if (new StudentPeer().getStudent(instance_tree.getSelectedItem().getLabel()) != null){
			if (contents_win.getFellow("grades_l").getSelectedCount() == 1){
				Grade DAOGrade = grades.get(contents_win.getFellow("grades_l").getSelectedIndex());
				semester.value = Constants.MAP_SEMESTER_VALUE.get(DAOGrade.getSemester()); 
				if (semester.value.equals(Constants.SUMMER)){
					year1.value = "" + (DAOGrade.getAcademicYear() - 1);
					year2.value = "" + (DAOGrade.getAcademicYear());
				}
				else{
					year1.value = "" + (DAOGrade.getAcademicYear());
					year2.value = "" + (DAOGrade.getAcademicYear() + 1);
				}
				grade.value = "" + DAOGrade.getGrade();
				course.value = DAOGrade.getCourse().getCourseCode();
				section.value = DAOGrade.getSectionName();
				credit.value = DAOGrade.getCredit();
				remarks.value = DAOGrade.getRemarks();
				grade_id.value = DAOGrade.getGradeId();
				grade_form_popup.open(self);
			}
			else
				alert("Select a grade");
		}
		else
			alert("Select a student");
	}
}



void delete (){
	if (new StudentPeer().getStudent(instance_tree.getSelectedItem().getLabel()) != null){
		if (contents_win.getFellow("grades_l").getSelectedCount() != 0){
			Iterator iter = contents_win.getFellow("grades_l").getSelectedItems().iterator();
			while(iter.hasNext()){
				Grade DAOGrade = grades.get(iter.next().getIndex());
				new GradePeer().deleteGrade(DAOGrade.getGradeId());
			}
			showInfo();
		}
		else
			alert("Select at least one grade");
	}
	else
		alert("Select a student");
}


void importData(){
	org.zkoss.util.media.Media media = Fileupload.get();
	if(media != null){
		java.io.Reader r = new java.io.BufferedReader(media.getReaderData());
		String line = null;
		StringBuffer buf = new StringBuffer(9999999);
			while ((line = r.readLine()) != null) {
			buf.append(line+"\r\n"); 
			}
		new registnet.dao.GradePeer().importGrades(buf.toString());
	}
}